
let RoadBlockPool = require('GameObjectPool').RoadBlock;


const Type = cc.Enum({
    SMALL: 1,
    MEDIUM: 2,
    BIG: 3
});


let RoadBlock = cc.Class({
    extends: require('BaseComponent'),
    mixins: [cc.EventTarget],

    properties: {
        type: {
            default: Type.SMALL,
            type: Type
        },

        hpLabel: cc.Label,

        moveSpeed: 120,

        x: {
            get() {
                return this.node.x;
            },
            set(val) {
                this.node.x = Math.max(this.boundaryRange[0], Math.min(val, this.boundaryRange[1]));
            },
            visible: false
        }
    },

    ctor() {
        this.hpType = 0;
        this.hp = 0;

        this.initialHp = 0;

        this.colors = [];

        this.isDied = false;

        this.isMoving = false;
        this.boundaryRange = [-Infinity, Infinity];
        this._boundaryIdx = 0;
    },
    update(dt) {
        if (!this.isMoving) return;

        this.x -= this.moveSpeed * dt;
        if (this.x == this.boundaryRange[this._boundaryIdx]) {
            this.changeMoveDirection();
        }
    },

    onCollisionEnter(other, self) {
        // cc.log('--BLOCK-C-ENTER:',other);

        let bullet = other.node.getComponent('Bullet');
        if (bullet) {
            this.emit('hit-bullet', bullet);
            return;
        }

        let roadBlock = other.node.getComponent('RoadBlock');
        if (roadBlock) {
            this.isMoving && this.changeMoveDirection();
        }
    },

    unuse() {
        this.isMoving = false;
    },
    reuse() {
        this.initialHp = 0;
        this.isDied = false;

        this.off('hit-bullet');
        this.off('die');

        this._super();
    },

    removeSelf() {
        RoadBlockPool.put(this.node);

        this._super();
    },

    setHp(hp) {
        if (hp < 0) cc.error('block hp invalid:', hp);

        if (!this.initialHp)
            this.initialHp = hp;

        this.hp = hp;

        if (hp < 1000) {
            this.hpLabel.string = hp;
        } else {
            this.hpLabel.string = Math.floor(hp / 1000) +':';
        }

        if (this.colors && this.initialHp && hp > 0) {
            this.node.color = this.colors[ Math.ceil(hp / this.initialHp * this.colors.length) - 1 ];
        }
    },
    attacked(damage) {
        this.setHp( Math.max(0, this.hp - damage) );

        if (this.hp == 0) {
            this.die();
        }
    },
    die() {
        if (this.isDied) return;
        this.isDied = true;

        this.emit('die');

        this.removeSelf();
    },

    setBoundary(range) {
        let width = this.width * this.anchorX;
        this.boundaryRange = [range[0] + width, range[1] - width];
    },
    move() {
        this.isMoving = true;
    },
    changeMoveDirection() {
        this.moveSpeed = -this.moveSpeed;
        this._boundaryIdx = this._boundaryIdx ^ 1;
    }
});

RoadBlock.Type = Type;